const fs = require('fs');
const path = require('path');
const ipcRenderer = require('electron').ipcRenderer;
const util = require('../../libs/util.js');
const curWin = require('electron').remote.getCurrentWindow();
new Vue({
  el: document.getElementById("root"),
  data() {
    return {
      form: {
        name: '',
        url: '',
        type: [],
        template: {},
        javascript: '',
        isRegx: false
      },
      projectName: '',
      parentWinId: ''
    }
  },
  created() {
    ipcRenderer.on('projectDetailWin-createApiWin', (event, args) => {
      this.projectName = args.projectName;
      this.parentWinId = args.projectDetailWinId;
    });
  },
  methods: {
    onSubmit() {
      if (this.form.name !== '' && this.form.url !== '' && this.form.type.length > 0) {
        if (this.projectName === "") {
          this.$message.error("数据读取错误");
        } else {
          const filePath = path.resolve("/data-mock", "projects", this.projectName, `${this.projectName}.json`);
          const jsonString = fs.readFileSync(filePath, { encoding: "utf8" });
          const json = JSON.parse(jsonString);
          if (this.form.url.charAt(0) === '/' && this.form.url.charAt(this.form.url.length - 1) === '/') {
            // this.form.url = this.form.url.substring(1, this.form.url.length - 1);
            this.form.isRegx = true;
            json.mocks.regx.push(this.form);
          } else if (util.type(this.form.url) === util.constant.objectType.string) {
            json.mocks.string[this.form.url] = this.form;
          }
          fs.writeFileSync(filePath, JSON.stringify(json, null, 4));
          require('electron').remote.BrowserWindow.fromId(this.parentWinId).webContents.send("pushApi", this.form);
          curWin.close();
        }
      } else {
        this.$message.warning("请填写完整");
      }
    },
    onCancel() {
      curWin.close();
    }
  }
})
